package com.imooc.infra.repository;

import com.imooc.business.domain.Collect;
import com.imooc.infra.mapping.CollectMapping;
import com.imooc.infra.repository.entity.TDataCenterCalculate;
import com.imooc.infra.repository.entity.TDataCenterCollect;
import com.imooc.infra.repository.service.ITDataCenterCollectService;
import lombok.Setter;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Repository
public class CollectRepository {

    @Setter(onMethod_ = @Autowired)
    private ITDataCenterCollectService collectService;

    @Setter(onMethod_ = @Autowired)
    private CollectMapping collectMapping;

    public Collect getById(Long id) {
        TDataCenterCollect collect = collectService.getById(id);
        return Optional.ofNullable(collect).map(collectMapping::toVo).orElse(null);
    }

    /**
     * 根据规则id查询列表
     * @param ruleId
     * @return
     */
    public List<Collect> listByRuleId(Long ruleId) {
        List<TDataCenterCollect> collects = collectService.listByRuleId(ruleId);
        return collects.stream().map(collectMapping::toVo).collect(Collectors.toList());
    }

    public boolean save(Collect collect) {
        if (Objects.isNull(collect)) {
            return Boolean.FALSE;
        }
        TDataCenterCollect dataCenterCollect = new TDataCenterCollect();
        BeanUtils.copyProperties(collect, dataCenterCollect);
        dataCenterCollect.setCollectWay(collect.getCollectWay().getSourceValue());
        return collectService.save(dataCenterCollect);
    }

    public List<Collect> saveCollect(Long ruleId, List<Collect> collects) {
        List<TDataCenterCollect> entityList = collects.stream().map(collectMapping::toEntity).
                peek(collect -> collect.setRuleId(ruleId)).collect(Collectors.toList());
        boolean saveBatch = collectService.saveBatch(entityList);
        if (saveBatch) {
            return entityList.stream().map(collectMapping::toVo).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    public Collect getByRuleIdAndEnName(Long ruleId, String enName) {
        TDataCenterCollect collect =  collectService.getByRuleIdAndEnName(ruleId, enName);
        return Optional.ofNullable(collect).map(collectMapping::toVo).orElse(null);
    }
}
